package com.kang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.entity.*;
import com.kang.mapper.*;
import com.kang.service.NotifyService;
import com.kang.util.ThreadLocalUtil;
import com.kang.vo.ParamInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NotifyServiceImpl extends ServiceImpl<NotifyMapper , Notify> implements NotifyService {

    @Autowired
    private NotifyMapper notifyMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private BookMarkMapper bookMarkMapper;

    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private ConcernMapper concernMapper;


    @Override
    public Integer insertNotify(Notify notify) {
        notify.setCreateTime(new Date());
        notify.setUpdateTime(new Date());
        notify.setViewNum(0);
        notify.setUserId(ThreadLocalUtil.getCurrentUser().getId());
        int insert = notifyMapper.insert(notify);
        if (insert == 1) {
            stringRedisTemplate.opsForValue().set("admin:view:" + notify.getId(), String.valueOf(0));
        }
        return insert;
    }

    @Override
    public Integer deleteNotify(Notify notify) {
        int i = baseMapper.deleteById(notify.getId());
        if (i == 1) {
            stringRedisTemplate.delete("admin:view:" + notify.getId());
        }
        return i;
    }

    @Override
    public Page<Notify> getNotifyPage(ParamInfo vo) {
        Page<Notify> page = new Page<>(vo.getPageNum(), vo.getPageSize());
        //查询分页数据
        QueryWrapper<Notify> wrapper = new QueryWrapper<>();
        wrapper.eq(vo.getStatus() != null,"status",vo.getStatus());
        wrapper.like(vo.getName() != null,"title",vo.getName());
        wrapper.between(vo.getStartTime() != null,"create_time",vo.getStartTime(),vo.getEndTime());
        Page<Notify> notifyPage = notifyMapper.selectPage(page, wrapper);
        List<Notify> records = notifyPage.getRecords();
        //对应公告发布名称
        List<Integer> collect = records.stream().map(Notify::getUserId).collect(Collectors.toList());
        //if判断防止空公告时多次访问数据库
        if (collect.size() != 0) {
            QueryWrapper<SysUser> userWrapper = new QueryWrapper<>();
            userWrapper.in(true,"id",collect);
            //获取所有发布者的用户名
            List<SysUser> sysUsers = userMapper.selectList(userWrapper);
            notifyPage.getRecords().forEach(v -> {
                for (SysUser sysUser : sysUsers) {
                    if (v.getUserId().equals(sysUser.getId())) {
                        v.setUsername(sysUser.getUsername());
                        break;
                    }
                }

                if (v.getContext().length() > 100) {
                    v.setContext(v.getContext().substring(0,100) + "...");
                }

                String viewNum = stringRedisTemplate.opsForValue().get("admin:view:" + v.getId());
                if (viewNum == null) {
                    stringRedisTemplate.opsForValue().set("admin:view:" + v.getId(),String.valueOf(v.getViewNum()));
                } else {
                    v.setViewNum(Integer.valueOf(viewNum));
                }
            });
        }

        return notifyPage;
    }

    @Override
    public Integer updateNotify(Notify notify) {
        notify.setUpdateTime(new Date());
        notify.setUserId(ThreadLocalUtil.getCurrentUser().getId());
        UpdateWrapper<Notify> wrapper = new UpdateWrapper<>();
        //此处更新内容，跟是否发布无关系
        wrapper.eq("id",notify.getId());
        wrapper.set("title",notify.getTitle());
        wrapper.set("context",notify.getContext());
        wrapper.set("photo_url",notify.getPhotoUrl());
        wrapper.set("user_id",notify.getUserId());
        wrapper.set("label_id",notify.getLabelId());
        wrapper.set("update_time",notify.getUpdateTime());
        return notifyMapper.update(null,wrapper);
    }

    @Override
    public Notify getNotifyById(Integer id) {
        Notify notify = notifyMapper.selectById(id);
        stringRedisTemplate.opsForValue().increment("admin:view:" + id);
        //redis中存的浏览量加1
        String viewNum = stringRedisTemplate.opsForValue().get("admin:view:" + id);
        assert viewNum != null;
        notify.setViewNum(Integer.valueOf(viewNum));
        //添加昵称和头像
        SysUser user = userMapper.selectById(notify.getUserId());
        notify.setUsername(user.getUsername());
        notify.setHeadUrl(user.getHeadUrl());
        //  查询标签名称
        if (notify.getLabelId() != null) {
            List<String> labelIdList = Arrays.stream(notify.getLabelId().split(",")).collect(Collectors.toList());
            QueryWrapper<Label> labelWrapper = new QueryWrapper<>();
            labelWrapper.in("id",labelIdList);
            List<String> labelNames = labelMapper.selectList(labelWrapper).stream().map(Label::getLabelName).collect(Collectors.toList());
            notify.setLabelNames(labelNames);
        }
        //统计图片路径
        List<String> collect = Arrays.stream(notify.getPhotoUrl().split(",")).collect(Collectors.toList());
        notify.setUrlList(collect);
        return notify;
    }

    @Override
    public Integer updateStatus(Notify notify) {
        notify.setUpdateTime(new Date());
        notify.setUserId(ThreadLocalUtil.getCurrentUser().getId());
        UpdateWrapper<Notify> wrapper = new UpdateWrapper<>();
        //此处更新内容，跟是否发布无关系
        wrapper.eq("id",notify.getId());
        wrapper.set("status",1);
        return notifyMapper.update(null,wrapper);
    }

    @Override
    public Page<Notify> getNotifyShow() {
        Page<Notify> page = new Page<>(1, 5);
        QueryWrapper<Notify> wrapper = new QueryWrapper<>();
        wrapper.last("order by create_time desc");
        return notifyMapper.selectPage(page,wrapper);
    }

}
